package com.jinhuhang.u2.invertmodule;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jinhuhang.u2.MyApplication;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.api.RetrofitUtils;
import com.jinhuhang.u2.common.base.activity.SimpleBaseActivity;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.entity.AccountBean;
import com.jinhuhang.u2.entity.ProjectDetail;
import com.jinhuhang.u2.entity.UserBean;
import com.jinhuhang.u2.invertmodule.adapter.SimpleFragmentPagerAdapter;
import com.jinhuhang.u2.invertmodule.fragment.FragmentProtocol;
import com.jinhuhang.u2.invertmodule.fragment.FragmentUserInfo;
import com.jinhuhang.u2.listener.Listener;
import com.jinhuhang.u2.myselfmodule.engine.bank.BankActivity;
import com.jinhuhang.u2.myselfmodule.engine.recharge.RechargeActivity;
import com.jinhuhang.u2.myselfmodule.engine.user.UserActivity;
import com.jinhuhang.u2.ui.DefaultDialog;
import com.jinhuhang.u2.ui.MainActivity;
import com.jinhuhang.u2.ui.customview.CustomToast;
import com.jinhuhang.u2.ui.customview.MyDialog;
import com.jinhuhang.u2.ui.customview.slipdetail.PullUpToLoadMore;
import com.jinhuhang.u2.ui.customview.slipdetail.PullUpToLoadMore1;
import com.jinhuhang.u2.util.RSAEncryptor;
import com.jinhuhang.u2.util.StringUtils;
import com.jinhuhang.u2.util.U2MD5Util;
import com.jinhuhang.u2.util.U2Util;
import com.jinhuhang.u2.util.UtilsCollection;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.http.ResultList;
import com.jinhuhang.u2.util.http.T;
import com.jinhuhang.u2.util.logger.Logger;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by caoxiaowei on 2017/8/30.
 */
public class TenderDetailActivity extends SimpleBaseActivity implements PullUpToLoadMore.ChangeUi {
    @Bind(R.id.yelid)
    TextView mYelid;
    @Bind(R.id.autotender)
    TextView mAutotender;
    @Bind(R.id.residue)
    TextView mResidue;
    @Bind(R.id.progressBar)
    ProgressBar mProgressBar;
    @Bind(R.id.progressnum)
    TextView mProgressnum;
    @Bind(R.id.interestpe)
    TextView mInterestpe;
    @Bind(R.id.monthtender)
    TextView mMonthtender;
    @Bind(R.id.startmoney)
    TextView mStartmoney;
    @Bind(R.id.invertnum)
    TextView mInvertnum;
    @Bind(R.id.invertlog)
    LinearLayout mInvertlog;
    @Bind(R.id.secure)
    LinearLayout mSecure;
    @Bind(R.id.changeimg)
    ImageView mChangeimg;
    @Bind(R.id.tabs)
    TabLayout mTabs;
    @Bind(R.id.viewPager1)
    ViewPager mViewPager1;
    @Bind(R.id.ptlm)
    PullUpToLoadMore1 mPtlm;
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.signz_4)
    TextView mSignz4;
    @Bind(R.id.account_num)
    TextView mAccountNum;
    @Bind(R.id.imageView8)
    ImageView mImageView8;
    @Bind(R.id.textView4)
    TextView mTextView4;
    @Bind(R.id.imageView9)
    ImageView mImageView9;
    @Bind(R.id.linebgf)
    View mLinebgf;
    @Bind(R.id.estimate1)
    TextView mEstimate1;
    @Bind(R.id.input_money)
    EditText mInputMoney;
    @Bind(R.id.setbtn)
    ImageView mSetbtn;
    @Bind(R.id.startmoney1)
    TextView mStartmoney1;
    @Bind(R.id.layre)
    LinearLayout mLayre;
    @Bind(R.id.caninvert1)
    TextView mCaninvert1;
    @Bind(R.id.invert_tender)
    TextView mInvertTender;
    @Bind(R.id.virtualMultiples)
    TextView mVirtualMultiples;
    @Bind(R.id.tiyanjin)
    LinearLayout mTiyanjin;
    @Bind(R.id.month_unit)
    TextView mMonthUnit;
    @Bind(R.id.start_unit)
    TextView mStartUnit;


    private ArrayList<Fragment> list_fragment = new ArrayList<>();                                //定义要装fragment的列表
    private ArrayList<String> list_title = new ArrayList<>();                                //定义要装fragment的列表
    private FragmentUserInfo mTwoFragment;            //热门收藏fragment
    private FragmentProtocol mthreeFragment;

    private SimpleFragmentPagerAdapter pagerAdapter;

    private ViewPager viewPager;

    private TabLayout tabLayout;

    int tenderid;
    int type;

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void initData() {
        super.initData();
        tenderid = getIntent().getIntExtra("id", 0);
        type = getIntent().getIntExtra("type", 0);
        if (type == 1) {
            mInvertTender.setEnabled(false);
            mInvertTender.setBackgroundColor(getColor(R.color.glay1));
        }

        mInputMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //删除“.”后面超过2位后的数据
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 3);
                        mInputMoney.setText(s);
                        mInputMoney.setSelection(s.length()); //光标移到最后
                    }
                }
                //如果"."在起始位置,则起始位置自动补0
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    mInputMoney.setText(s);
                    mInputMoney.setSelection(2);
                }

                //如果起始位置为0,且第二位跟的不是".",则无法后续输入
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        mInputMoney.setText(s.subSequence(0, 1));
                        mInputMoney.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

                String votalAccountStr = mInputMoney.getText().toString();
                votalAccountStr = votalAccountStr.trim();
                if (!StringUtils.isEmpty(votalAccountStr)) {
                    if (votalAccountStr.lastIndexOf(".")==votalAccountStr.length()-1){
                        votalAccountStr=votalAccountStr+"0";
                    }
                    if (StringUtils.isNumeric(votalAccountStr)) {
                        BigDecimal result = U2Util.caculateInterest(mProjectDetail.getStyle(), mProjectDetail.getApr(), mProjectDetail.getTimeLimit(), votalAccountStr, String.valueOf(mProjectDetail.getTimeLimitType()));
                        result = result.setScale(2, BigDecimal.ROUND_HALF_UP);
                        mEstimate1.setText(result.toString());
                    }
                    else {
                        CustomToast.showToast("请输入正确数字");
                    }
                } else {
                    mEstimate1.setText("0");
                }
            }
        });


        //初始化各fragment
        mTwoFragment = new FragmentUserInfo();
        mthreeFragment = new FragmentProtocol();
        //将fragment装进列表中
        list_fragment.add(mTwoFragment);
        list_fragment.add(mthreeFragment);
        list_title.add("借款人信息");
        //list_title.add("债权明细");
        list_title.add("服务协议");

        pagerAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), this, list_fragment, list_title);
//        viewPager = (ChildViewPager) findViewById(R.id.viewpager);
        viewPager = (ViewPager) findViewById(R.id.viewPager1);
        viewPager.setAdapter(pagerAdapter);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                setIndicator(tabLayout, 10, 10);
            }
        });
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        getData();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_tender_detail;
    }

    public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());
        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

    @OnClick({R.id.invertlog, R.id.secure, R.id.back, R.id.invert_tender, R.id.setbtn})
    void onclick(View view) {
        switch (view.getId()) {
            case R.id.invertlog:

                Intent intent = new Intent(this, InvertLogActivity.class);
                intent.putExtra("id", tenderid);
                startActivity(intent);
                break;
            case R.id.secure:
                Intent intent1 = new Intent(this, ScanActivity.class);
                intent1.putExtra("type", "creditor");
                startActivity(intent1);
                break;
            case R.id.invert_tender:
                invert();
                break;
            case R.id.setbtn:
                double start = StringUtils.isEmpty(mProjectDetail.getLowestAccount()) ? 0 : Double.parseDouble(mProjectDetail.getLowestAccount());
                if (usermoney>start){
                    mInputMoney.setText(usermoney/start*start + "");
                }else {
                    mInputMoney.setText(usermoney + "");
                }
                break;
            case R.id.back:
                finish();
                break;
        }
    }

    @Override
    public void change(boolean ch) {
        if (ch) {
            mChangeimg.setBackgroundResource(R.drawable.touzi_xiangshanglachakanxiangqing);
        } else {
            mChangeimg.setBackgroundResource(R.drawable.touzi_xiangxialachakanbiaodi);
        }
    }

    private void goBindBank(DefaultDialog defaultDialog) {
        //去绑卡
        defaultDialog.setContent("您尚未完成实名认证,请先进行绑定银行卡操作");
        defaultDialog.setLeft("去认证");
        defaultDialog.setOnNormalAlertDialogChooseClickListener(new Listener.OnNormalAlertDialogChooseClickListener() {
            @Override
            public void onLeft() {
                startActivity(new Intent(TenderDetailActivity.this, BankActivity.class));
            }

            @Override
            public void onRight() {

            }
        });
    }

    AccountBean accountBean = MyApplication.mSpUtil.getAccount();

    private void goRecharge() {

        Intent intent = new Intent(this, RechargeActivity.class);
        intent.putExtra("userMoney", accountBean.getUseMoney());
        startActivity(intent);
    }

    public void invert() {
        double input = 0;
        if (MainActivity.userbean == null && MainActivity.uid.equals("0")) {
            MyDialog.toDisplayActivity1(this, 1);//去登陆
            return;
        }
        if (!MainActivity.checktoken) {
            if (MainActivity.tip!=null) {
                CustomToast.showToast(MainActivity.tip);
            }
            MainActivity.userbean=null;
            MyApplication.mSpUtil.setUser(null);
            Intent intent=new Intent(MyApplication.getContext(), UserActivity.class);
            intent.putExtra("type",UserActivity.LOGIN);
            startActivity(intent);
            finish();
            return;
        }
        if (MainActivity.userbean.getAssessment()==0){
            MyDialog.showAssessment(this);
            return;
        }
        UserBean user = MyApplication.mSpUtil.getUser();
        String cardNo = RSAEncryptor.androidDecryt(user.getCardNo());
        Logger.e(cardNo + new Gson().toJson(user));
        if (TextUtils.isEmpty(cardNo)) {
            /**
             * 未认证绑卡失败
             */
            DefaultDialog defaultDialog = new DefaultDialog(this);
            defaultDialog.show();
            goBindBank(defaultDialog);
            return;
        } else if (StringUtils.isEmpty(user.getUseMoney())) {
            CustomToast.showToast("余额不足，请充值！");
           // goRecharge();
            return;
        }
        double start = StringUtils.isEmpty(mProjectDetail.getLowestAccount()) ? 0 : Double.parseDouble(mProjectDetail.getLowestAccount());
        double end = StringUtils.isEmpty(mProjectDetail.getMostAccount()) ? 0 : Double.parseDouble(mProjectDetail.getMostAccount());
        if (mProjectDetail.getSort() == 10) {
            MyDialog.openAuto(this, accountBean.getAotuType());
            return;
        }
        try {
            input = Double.parseDouble(mInputMoney.getText().toString());

            if ( Double.parseDouble(user.getUseMoney())<input){
                CustomToast.showToast("余额不足，请充值！");
                return;
            }
            if (input < start) {
                CustomToast.showToast("出借金额不能低于最小出借金额！");
                return;
            }

            if (end > 0 && input > end) {
                CustomToast.showToast("出借金额不能高于最高出借金额！");
                return;
            }
            if (input > usermoney) {
                CustomToast.showToast("出借金额不能高于可出借金额！");
                return;
            }
        } catch (Exception o) {
            CustomToast.showToast("请输入正确的数字！");
        }
        if (!StringUtils.isEmpty(mProjectDetail.getTenderPassword()) && !mProjectDetail.getTenderPassword().equals("0")) {
            checkPwd(mProjectDetail.getTenderPassword());
        }else {
            Intent intent = new Intent(TenderDetailActivity.this, ProjectBuyActivity.class);
            intent.putExtra("bid", tenderid);
            intent.putExtra("money", String.valueOf(input));
            intent.putExtra("mProjectDetail", mProjectDetail);
            intent.putExtra("type", 2);
            startActivity(intent);
        }
    }
    Dialog dialog;

    public void checkPwd(String pwd) {
        if (dialog != null) {
            dialog.cancel();
        }
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_invertpwd, null);
        TextView getDetail = (TextView) view.findViewById(R.id.checkpwd);
        TextView errorstr = (TextView) view.findViewById(R.id.errorstr);
        EditText input = (EditText) view.findViewById(R.id.pwd);
        dialog = new Dialog(this, R.style.dialog);
        final WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.alpha = 1.0f;
        dialog.setCanceledOnTouchOutside(false);
        dialog.getWindow().setAttributes(lp);
        dialog.setContentView(view);
        dialog.show();
        getDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pwd.equals(U2MD5Util.encryption(input.getText().toString().trim()))) {
                    Intent intent = new Intent(TenderDetailActivity.this, ProjectBuyActivity.class);
                    intent.putExtra("mProjectDetail", mProjectDetail);
                    intent.putExtra("bid", tenderid);
                    intent.putExtra("money", mInputMoney.getText().toString());
                    intent.putExtra("type", 2);
                    startActivity(intent);
                    dialog.dismiss();
                } else {
                    errorstr.setVisibility(View.VISIBLE);
                }
            }
        });
    }
    public void getData() {
        showDialog("");
        addSubscription(RetrofitUtils.getInstance().build()
                .prodectDetail(MainActivity.uid, String.valueOf(tenderid))
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<ProjectDetail>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<ProjectDetail> data) {
                        if (data.code == Constant.SUCCESS_CODE)
                            showData(data.getSingleData());

                    }

                }));
        if (MainActivity.userbean!=null) {
            addSubscription(RetrofitUtils.getInstance().build()
                    .checkToken(MainActivity.userbean.getUserId(), MainActivity.userbean.getToken())
                    .compose(T.defaultScheduler())
                    .subscribe(new ResultList<HttpWrapperList<String>>() {

                        @Override
                        protected void onSuccess(HttpWrapperList<String> o) {
                            if (o.getCode() == 200) {
                                MainActivity.checktoken = true;
                            } else {
                                //token 失效
                                MainActivity.checktoken = false;
                                MainActivity.tip=null;
                                if (o.getCode()!=301) {
                                    MainActivity.tip=o.getInfo();
                                }
                            }
                        }

                    }));
        }
    }

    double sum = 0;
    double most = 0;
    double sumyes = 0;
    double sumaccount = 0;
    double usermoney = 0;
    ProjectDetail mProjectDetail;

    protected void showData(ProjectDetail data) {
        dissDialog();
        mProjectDetail = data;
        mthreeFragment.setUrl(0, data.getUrl());
        mTwoFragment.initData(data);
        mTvTitle.setText(data.getTitle());
        sum = StringUtils.isEmpty(mProjectDetail.getAccount()) ? 0 : Double.parseDouble(mProjectDetail.getAccount());
        most = StringUtils.isEmpty(mProjectDetail.getMostAccount()) ? 0 : Double.parseDouble(mProjectDetail.getMostAccount());
        sumyes = StringUtils.isEmpty(mProjectDetail.getAccountYes()) ? 0 : Double.parseDouble(mProjectDetail.getAccountYes());
        sumaccount = StringUtils.isEmpty(mProjectDetail.getSumAmount()) ? 0 : Double.parseDouble(mProjectDetail.getSumAmount());
        //1、优先级为10时，系统显示“自动投标专享”标签，并对未设置自动投标的用户进行拦截
        //  2、优先级在[0,10)区间时，页面不显示“自动投标专享”标签
        if (data.getSort() != 10) {
            mAutotender.setVisibility(View.GONE);
        }
        if (Double.parseDouble(data.getVirtualMultiples()) <= 0) {
            mTiyanjin.setVisibility(View.INVISIBLE);
        } else {
            mVirtualMultiples.setText("送" + data.getVirtualMultiples() + "倍体验金");
        }
        mInvertnum.setText(data.getTenderCount()+"");
        mYelid.setText(data.getApr());
        mAccountNum.setText(data.getAccount() + "");
        mProgressBar.setProgress((int) (sumyes*100 / sum));
        mProgressnum.setText(String.format("%.2f", (sumyes*100 / sum)) + "%");
        mResidue.setText("剩余：" + (sum - sumyes) + "元");
        if (data.getStyle() == 0) {
            mInterestpe.setText("等额本息");
        } else if (data.getStyle() == 1) {
            mInterestpe.setText("先息后本");
        } else if (data.getStyle() == 2) {
            mInterestpe.setText(" 到期本息");
        }
        mInputMoney.setText(data.getLowestAccount() + "");
        mMonthtender.setText(data.getTimeLimit() + "");
        if (data.getTimeLimitType() == 1) {
            mMonthUnit.setText("个月");
        } else if (data.getTimeLimitType() == 2) {
            mMonthUnit.setText("年");
        } else if (data.getTimeLimitType() == 3) {
            mMonthUnit.setText("天");
        }
        mStartmoney.setText(data.getLowestAccount() + "");
        mStartmoney1.setText(data.getLowestAccount() + "元");

        if (StringUtils.isEmpty(mProjectDetail.getMostAccount()) || Double.parseDouble(mProjectDetail.getMostAccount())<=0) {
            usermoney = sum - sumyes;
        } else {
            usermoney = most - sumaccount;
            if (usermoney>( sum - sumyes)){
                usermoney = sum - sumyes;
            }
        }
        mCaninvert1.setText(UtilsCollection.formatNumber1(usermoney)+ "元");
        BigDecimal result = U2Util.caculateInterest(data.getStyle(), data.getApr(), data.getTimeLimit(), data.getLowestAccount(), String.valueOf(data.getTimeLimitType()));
        result = result.setScale(2, BigDecimal.ROUND_UP);
        mEstimate1.setText(result.toString());
        final long[] time = {data.getValidTimeStart() - data.getLocalTime()};
        if (data.getStatus() == 1) {

            if (time[0] > 0) {
                mInvertTender.setEnabled(false);
                Timer timer = new Timer();

                timer.schedule(new TimerTask() {
                    public void run() {
                        Message message = mHandler.obtainMessage();
                        time[0] -= 1000;
                        if (time[0] < 1000) {
                            timer.cancel();
                            message.what = 2;
                            mHandler.sendMessage(message);
                        }
                        long hh = time[0] / 1000 / (60 * 60);
                        long mm = time[0] / 1000 % (60 * 60) / 60;
                        long ss = time[0] / 1000 % (60 * 60) % 60;

                        //        Log.i("wwwwww"+ holdView.time/1000+":"+holdView.time / 1000/(60*60)+":"+ (holdView.time / 1000%(60*60))%60,hh + ":" + mm + ":" + ss);
                        message.obj = +hh + ":" + mm + ":" + ss;
                        message.what = 1;
                        mHandler.sendMessage(message);
                    }
                }, 0, 1000);
            }
        } else if (data.getStatus() == 2) {
            mInvertTender.setEnabled(false);
            mInvertTender.setText("已满");
        //    mInvertTender.setBackgroundColor(getResources().getColor(R.color.glay1));
        }
//        else if (usermoney<=0) {
//            mInvertTender.setEnabled(false);
//            mInvertTender.setText("已满标");
//            //     mInvertProject.setBackgroundColor(getResources().getColor(R.color.glay1));
//        }
        else if (data.getStatus() == 3) {
            mInvertTender.setEnabled(false);
            mInvertTender.setText("服务中");
            mInvertTender.setBackgroundColor(getResources().getColor(R.color.glay1));
        } else if (data.getStatus() == 5) {
            mInvertTender.setEnabled(false);
            mInvertTender.setText("服务结束");
            mInvertTender.setBackgroundColor(getResources().getColor(R.color.glay1));
        }
        else if (data.getStatus() == -2 ) {
            mInvertTender.setEnabled(false);
            mInvertTender.setText("已流标");
            mInvertTender.setBackgroundColor(getResources().getColor(R.color.glay1));
        }
    }
    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                mInvertTender.setEnabled(false);
                mInvertTender.setText(msg.obj + "");
            } else if (msg.what == 2) {
                mInvertTender.setEnabled(true);
                mInvertTender.setText("立即投资");
            }
            return false;
        }
    });
}
